<?php

class Model2servController extends Controller {

    public $defaultAction = 'admin';

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';
    public $menu = [
        //0 =>['label'=>'Список ','url'=>['index'],],
        10 => ['label' => 'Управление ', 'url' => ['admin'],],
        20 => ['label' => 'Создать ', 'url' => ['create'], 'prim' => true],
    ];

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'getService', 'priceHistory', 'copy', 'copy2'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('getData', 'getDataByUrl'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionCopy() {
        // mTools::copyModelService();

        if (isset($_POST['from']) && isset($_POST['to'])) {
//             echo '<pre>';
//        print_r($_POST);
            $fromID = json_decode($_POST['from'], true);
            $toID = json_decode($_POST['to'], true);
//            echo $fromID['id'];
//            echo $toID['id'];
//            exit;
            if (mTools::copyModelService((int) $fromID['id'], (int) $toID['id']))
                $this->redirect(array('update', 'id' => (int) $toID['id']));
        }
        $this->render('copy');
    }

    public function actionCopy2() {
        if (isset($_POST['fromUrl']) && isset($_POST['toUrl'])) {
            $fromUrl = parse_url($_POST['fromUrl']);
            $toUrl = parse_url($_POST['toUrl']);
            $fromID = Page::model()->find('"pageUrl" = \'' . substr($fromUrl['path'], 1, strlen($fromUrl['path'])) . '\'')->pageId;
            $toID = Page::model()->find('"pageUrl" = \'' . substr($toUrl['path'], 1, strlen($toUrl['path'])) . '\'')->pageId;
            if (mTools::copyModelService((int) $fromID, (int) $toID)) {
                Yii::app()->user->setFlash('save', 'Ваши изменения отправлены на сервер для обновления, они будут доступны пользователям через некоторое время.');
                $this->refresh();
            }
        }
        $this->render('copy2');
    }

    public function actionGetData() {
        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['id'])) {
                $c = new CDbCriteria();
                $c->select = '"pageId", "pageTitle"';
                $c->addCondition("\"pageParent\" = '{$_POST['id']}' AND \"pageType\" = '{$_POST['to']}'");
                $models = Page::model()->findAll($c);
                echo CHtml::tag
                        ('option', array('value' => 0), CHtml::encode('--'), true);
                foreach ($models as $value => $subcategory) {
                    echo CHtml::tag
                            ('option', array('value' => $subcategory['pageId']), CHtml::encode($subcategory['pageTitle']), true);
                }
                return;
            } else
                throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionGetDataByUrl() {
        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['id'])) {
                foreach (Yii::app()->params['categories'] as $cat) {
                    if (!empty($cat['faqUrl'])) {
                        $arr1[] = $cat['faqUrl'];
                        $arr2[] = $cat['pageUrl'];
                    }
                }
                $url = str_replace($arr1, $arr2, $_POST['id']);

                $a = new CDbCriteria();
                $a->select = '"pageId"';
                $a->addCondition("\"pageUrl\" = '{$url}'");
                $id = Page::model()->find($a)->pageId;
                $c = new CDbCriteria();
                $c->select = '"pageUrl", "pageTitle"';
                $c->addCondition("\"pageParent\" = '{$id}' AND \"pageType\" = '{$_POST['to']}'");
                $models = Page::model()->findAll($c);
                echo CHtml::tag
                        ('option', array('value' => ''), CHtml::encode('--'), true);
                foreach ($models as $value => $subcategory) {
                    echo CHtml::tag
                            ('option', array('value' => $subcategory['pageUrl']), CHtml::encode($subcategory['pageTitle']), true);
                }
                return;
            } else
                throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function getChartData($modelID) {
        $sql = "SELECT \"linkId\", \"serviceId\" FROM {{_model2serv}} WHERE \"modelId\" = '$modelID'";
        $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();

        foreach ($models as $model) {
            $data = array();
            $prices = Price2item::model()->findAll("\"itemId\" = " . $model['linkId']);
            foreach ($prices as $price) {
                $data[] = array($price['priceChangeDate'], (int) $price['priceSum']);
            }
            $services[] = array('name' => (string) Services::model()->findByPk($model['serviceId'])->serviceTitle, 'data' => $data);
        }
        return json_encode($services);
    }

    public function actionPriceHistory($id) {

        $this->render('chart', array('id' => $id));
    }

    public function actionGetService() {
        if (Yii::app()->request->isAjaxRequest && isset($_POST['id'])) {
            $c = new CDbCriteria();
            $c->select = '"serviceId", "serviceSort", "serviceTitle"';
            $c->addCondition("\"serviceCategory\" = '" . $_POST['catID'] . "' order by \"serviceSort\"");
            $models = Services::model()->findAll($c);
            $options = array('В наличии', 'Под заказ', 'Нет в наличии');

            $selects = '';
            $regions = Yii::app()->params['regions'];
            $sqlP = "SELECT \"priceAll\", \"priceSum\", \"priceAvailable\", \"priceRegionId\", \"itemId\" FROM mb__price2item WHERE \"itemType\"='link' and \"itemId\" in 
			(SELECT \"linkId\" FROM mb__model2serv WHERE \"modelId\"='" . $_POST['id'] . "') ORDER BY \"itemId\"";
            $prices = Yii::app()->db->getCommandBuilder()->createSqlCommand($sqlP)->queryAll();

            foreach ($prices as $pk => $pv) {
                $prcs[$pv['itemId']][$pv['priceRegionId']] = $pv;
            }
            $sql = "SELECT * FROM {{_model2serv}} WHERE \"modelId\" = '" . $_POST['id'] . "'";
            $m2s = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();

            foreach ($m2s as $k2s => $v2s) {
                $s[$v2s['serviceId']] = $v2s;
            }

            foreach ($models as $model):
                $part = '';
                $active = 1;
                if (isset($_POST['action'])) {
                    $inputs = '';
                    $block = !isset($s[$model->serviceId]) ? '' : $s[$model->serviceId]['blockNo'];
                    $select = '';
                    if (isset($s[$model->serviceId])) {
                        $price = '5';
                        $checked = 'checked';
                        $disabled = '';
                        $sort = $s[$model->serviceId]['sort'];
                        $active = $s[$model->serviceId]['active'];
                    } else {
                        $checked = '';
                        $price = '';
                        $disabled = 'disabled';
                        $sort = $model->serviceSort;
                    }
                } else {

                    $active = 1;
                    $price = '';
                    $block = '';
                    $sort = $model->serviceSort;
                    $select = '';
                    $checked = '';
                    $disabled = 'disabled';
                }
                foreach ($regions as $key => $value) {
                    if (isset($s[$model->serviceId]) && isset($prcs[$s[$model->serviceId]['linkId']][$value['regionId']])) {
                        $price = $prcs[$s[$model->serviceId]['linkId']][$value['regionId']]['priceSum'];
                        $nalichie = $prcs[$s[$model->serviceId]['linkId']][$value['regionId']]['priceAvailable'];
                    } else {
                        $price = '';
                        $nalichie = 0;
                    }

                    $p = !empty($price) ? 'value=\'' . $price . '\'' : '';
                    if (isset($s[$model->serviceId]) && isset($prcs[$s[$model->serviceId]['linkId']][$value['regionId']]))
                        $priceAll = $prcs[$s[$model->serviceId]['linkId']][$value['regionId']]['priceAll'];
                    $pAll = !empty($priceAll) ? 'value=\'' . $priceAll . '\'' : '';
                    if ($key == 1)
                        $inputs .= '<div style="text-align:left;"><span style="float: left; width: 125px;">Обшая цена</span>'
                                . '<input name="priceAll[' . $model->serviceId . ']" ' . $pAll . ' ' . $disabled . ' type="text" size="7"> <button type="button" style="margin-top: 4px;" class="btn btn-primary btn-small changeAll">Для всех</button>' .
                                '</div>';
                    $inputs .= '<div style="text-align:left;"><span style="float: left; width: 125px;">' . $value['regionTitle'] . '</span> '
                            . '<input name="price[' . $model->serviceId . '][' . $value['regionId'] . ']" ' . $p . ' ' . $disabled . ' type="text" size="2">' .
                            CHtml::dropDownList('nalichie[' . $model->serviceId . '][' . $value['regionId'] . ']', $nalichie, $options, array('style' => 'width:125px;', 'disabled' => $disabled)) .
                            '</div>';
                }
                $linkID = isset($s[$model->serviceId]['linkId']) ? $s[$model->serviceId]['linkId'] : '';
                echo '<tr class="' . $checked . '">
						<td>
						<input name="changes[' . $model->serviceId . ']" type="hidden" value="' . $model->serviceId . '" disabled="disabled">	
							<div class="checkbox check-default">
							<input type="hidden" name="linkId[]" ' . $disabled . ' value="' . $linkID . '">
								<input name="services[]" type="checkbox" value="' . $model->serviceId . '" id="ch-' . $model->serviceId . '" ' . $checked . '>
								<label for="ch-' . $model->serviceId . '"></label>
							</div>
						</td>
						<td class="text-center">' . $model->serviceTitle . '</td>						
						<td class="text-center">						
						' . $inputs . '	
						</td>
						<td class="text-center"><input name="block[' . $model->serviceId . ']" type="text" size="2" value="' . $block . '" ' . $disabled . '></td>	
						<td class="text-center"><input class="sort" name="sort[' . $model->serviceId . ']" type="text" size="2" value="' . $sort . '" ' . $disabled . '></td>							
						<td class="text-center"><span style="font-size:9px;">' . CHtml::checkBox('akt[' . $model->serviceId . ']', $active, array('value' => 1, 'disabled' => $disabled, 'class' => 'active')) . '</span></td>
					</tr>';
            endforeach;
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates and updates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate($id) {
        if (Yii::app()->user->name['userEmail'] == 'x8.zakupka@gmail.com') {
            Yii::app()->getController()->redirect('/x8/main/permission');
            throw new CHttpException(404, 'У вас недостаточно прав доступа для этой операции');
        }
        $model = $this->loadModel($id);
        if ($model === null) {
            $model = new Model2serv;
        }
        $brands = Page::model()->findByPk($id);
        $cats = Page::model()->findByPk($brands->pageParent);
        $model->category = $cats->pageParent;
        $model->brand = $brands->pageParent;
        $model->modelId = $id;
        $this->performAjaxValidation($model);

        if (isset($_POST['Model2serv'])) {
            if (isset($_POST['delete'])) {
                foreach ($_POST['delete'] as $keyA => $valueA) {
                    $sql = "DELETE FROM mb__model2serv WHERE \"linkId\" = '$valueA'";
                    Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
                }
            }
            if (isset($_POST['changes'])) {
                $this->backgroundUpdate($_POST);
            }
            Yii::app()->user->setFlash('save', 'Ваши изменения отправлены на сервер для обновления, они будут доступны пользователям через некоторое время.');
            $this->redirect(array('admin'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function backgroundUpdate(&$post) {

        foreach ($post['changes'] as $key => $value) {
            $ch = Model2serv::model()->find("\"modelId\" = '{$post['Model2serv']['modelId']}' AND \"serviceId\" = '{$value}'");
            $m = $ch === NULL ? new Model2serv : $ch;
            $m->modelId = $post['Model2serv']['modelId'];
            $m->serviceId = $value;
            $m->blockNo = $post['block'][$key];
            $m->sort = $post['sort'][$key];
            //$m->available = $_POST['nalichie'][$key];
            $m->active = !isset($post['akt'][$key]) ? 0 : $post['akt'][$key];
            $m->save(false);
            $sql = "DELETE FROM {{_price2item}} WHERE \"itemId\" = '" . $m->linkId . "'";
//			echo 'delete: '.$sql.'<br />';
            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();

            foreach ($post['price'][$value] as $regionID => $price) {
                $pAll = empty($post['priceAll'][$value]) ? 'Звоните' : $post['priceAll'][$value];
                $sql = "INSERT INTO {{_price2item}} (\"itemType\", \"itemId\", \"priceChangeDate\", \"priceSum\", \"priceRegionId\", \"priceAvailable\", \"priceAll\") VALUES ('link', '" . $m->linkId . "', '" . time() . "', '{$price}', '$regionID', '{$post['nalichie'][$value][$regionID]}', '{$pAll}')";
                Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();
//						echo 'insert: '.$sql.'<br />';					
            }
            usleep(50000);
        }
//		print_r($post['price'][$value]);exit;
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->user->name['userEmail'] == 'x8.zakupka@gmail.com') {
            Yii::app()->getController()->redirect('/x8/main/permission');
            throw new CHttpException(404, 'У вас недостаточно прав доступа для этой операции');
        }
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = $this->loadModel($id);
            $model->delete();
//			$sql = "DELETE FROM {{_model2serv}} WHERE modelId = '$model->modelId'";
//			Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        if (Yii::app()->user->name['userEmail'] == 'x8.zakupka@gmail.com') {
            Yii::app()->getController()->redirect('/x8/main/permission');
            throw new CHttpException(404, 'У вас недостаточно прав доступа для этой операции');
        }
        $dataProvider = new CActiveDataProvider('Model2serv');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        if (Yii::app()->user->name['userEmail'] == 'x8.zakupka@gmail.com') {
            Yii::app()->getController()->redirect('/x8/main/permission');
            throw new CHttpException(404, 'У вас недостаточно прав доступа для этой операции');
        }
        $model = new Model2servView('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Model2servView'])) {
            $model->attributes = $_GET['Model2servView'];
        }

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Model2serv the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Model2serv::model()->find('"modelId" = ' . (int) $id);
//		if ($model === null) {
//			throw new CHttpException(404, 'The requested page does not exist.');
//		}
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Model2serv $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'model2serv-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
